/**
 * Teacher.js
 */
$(document).ready(function() {

	$("#main-nav li ul").hide();
	$("#main-nav li a.current").parent().find("ul").slideToggle("slow");
	$("#main-nav li a.nav-top-item").click(function() {
		$(this).parent().siblings().find("ul").slideUp("normal");
		$(this).next().slideToggle("normal");
		$(this).parent().siblings().find("a.nav-top-item").removeClass('current');
		$(this).addClass('current');
		
		$.ajax({
			url : $(this).attr('href'),
			cache: false,
			success : function(msg) {
				$("#main-content-wrapper").html(msg);
			}
		});
		return false;
	});
	
	$("#main-nav li .nav-top-item").hover(function() {
		$(this).stop().animate({
			paddingRight : "25px"
		}, 200);
	}, function() {
		$(this).stop().animate({
			paddingRight : "15px"
		});
	});
	
	$("#main-nav li ul a").click(function() {
		$(this).parent().parent().find('a').removeClass('current');
		$(this).addClass('current');
	});
	
	$('a.createQuiz').live('click', function() {
		if(privilege != 0) {
			alert('你没有创建试题的权限！');
			return false;
		}
		if(!confirm('如果已经创建过试题，请不要再次创建！')) {
			return false;
		}
		$.post($(this).attr('href'), function(msg) {
			alert(msg);
		});
		return false;
	});
	
	$('a.addTeacher').live('click', function() {
		if(privilege != 0) {
			alert('你没有权限执行该操作！');
			return false;
		}
		$.facebox({div: '#add-teacher'});
	});
	
	$('a.queryTeacher').live('click', function() {
		if(privilege != 0) {
			alert('你没有权限执行该操作！');
			return false;
		}
		$.facebox({div: '#teacher-info-query'});
	});
	
	/**
	 * Query Management
	 */
	$('#secondaryCollege').live('change', function() {
		var $this = $(this);
		var $body = $('body');
		var majorSelectNode = $this.next();
		var major = $body.data('major');
		var addMajorOptionsToSelectNode = $body.data('addMajorOptionsToSelectNode');
		majorSelectNode.empty();
		addMajorOptionsToSelectNode(majorSelectNode, major[$this.val()]);
	});
	
 	$('div.filter-criteria input').live('focusin', function() {
 		var $this = $(this);
 		if($this.val() == $body.data($this.attr('id'))) {
	 		$(this).val('');
 		}
 	});
 	
 	$('div.filter-criteria input').live('focusout', function() {
 		var $this = $(this);
 		if($this.val() == '') {
 			$this.val($body.data($this.attr('id')));
 		}
 	});
	
 	/**
 	 * Test Result Query
 	 */
	$('#sBtn').live('click', function() {
		
		var $body = $('body');
		var quizRecordQueryForm = $(this).parent().parent();
		
		var clazz = quizRecordQueryForm.find('#clazz');
		var sno = quizRecordQueryForm.find('#sno');
		var name = quizRecordQueryForm.find('#name');
		var age = quizRecordQueryForm.find('#age');
		var lowestTotalScore = quizRecordQueryForm.find('#lowest-total-score');
		var lowestNopi = quizRecordQueryForm.find('#lowest-nopi');
		var factorValue = quizRecordQueryForm.find('#factor-value');
		var questionValue = quizRecordQueryForm.find('#question-value');
		
		if(clazz.val() != $body.data(clazz.attr('id')) && !/^[A-Za-z]\d{4}$/.test(clazz.val())) {
			alert("输入有错，请检查所输入班级...");
			return;
		}
		if(sno.val() != $body.data(sno.attr('id')) && !/^\d{11,13}$/.test(sno.val())) {
			alert("输入有错，请检查所输入学号...");
			return;
		}
		if(age.val() != $body.data(age.attr('id')) && !/^\d{2,3}$/.test(age.val())) {
			alert("输入有错，请检查所输入年龄...");
			return;
		}
		if(lowestTotalScore.val() != $body.data(lowestTotalScore.attr('id')) && !/^[1-9]\d{0,2}$/.test(lowestTotalScore.val())) {
			alert("输入有错，请检查所输入最低总分...");
			return;
		}
		if(lowestNopi.val() != $body.data(lowestNopi.attr('id')) && !/^\d{1,2}$/.test(lowestNopi.val())) {
			alert("输入有错，请检查所输入最低阳性项目数...");
			return;
		}
		if(factorValue.val() != $body.data(factorValue.attr('id')) && !/^[1-5]$/.test(factorValue.val())) {
			alert("输入有错，请检查因子项输入值...");
			return;
		}
		if(questionValue.val() != $body.data(questionValue.attr('id')) && !/^[1-5]$/.test(questionValue.val())) {
			alert("输入有错，请检查题目输入值...");
			return;
		}
		
		$(document).trigger('close.facebox');
		setTimeout(queryUsers,250);
		
		function queryUsers() {
			if(clazz.val() == $body.data(clazz.attr('id'))) {
				clazz.val('-1');
			}
			if(sno.val() == $body.data(sno.attr('id'))) {
				sno.val('-1');
			}
			if(name.val() == $body.data(name.attr('id'))) {
				name.val('-1');
			}
			if(age.val() == $body.data(age.attr('id'))) {
				age.val('-1');
			}
			if(lowestTotalScore.val() == $body.data(lowestTotalScore.attr('id'))) {
				lowestTotalScore.val('-1');
			}
			if(lowestNopi.val() == $body.data(lowestNopi.attr('id'))) {
				lowestNopi.val('-1');
			}
			
			$.post(quizRecordQueryForm.attr('action'), quizRecordQueryForm.serialize(), function(resp) {
				var users = $.parseJSON(resp);
				
				var queryResultTable = $('#query-result-table');
				var queryResultTableTbody = queryResultTable.find('tbody');
				var queryResultTableTfoot = queryResultTable.find('tfoot');
				queryResultTableTbody.empty();
				queryResultTableTfoot.empty();
			
				var recordNumOfPerPage = 10;
				var visiblePages = 5;
				var totalPages = Math.ceil(users.length / recordNumOfPerPage);
				var remainder = users.length % recordNumOfPerPage;

				if(users.length == 0) {
					queryResultTableTbody.append("<tr><td colspan='6' style='padding:50px 0 50px 0;'>您所查询的数据不存在。</td></tr>");
					return;
				}
				
				/**
				 * Append Users To TBody
				 */
				function appendUsersToTbody(appendedUsers) {
					for(var i=0; i < appendedUsers.length; i++) {
						var user = appendedUsers[i];
						if(i % 2 == 0) {
							var trTagTbody = "<tr id='" + i + "' class='alt-row'>" +
												"<td>" + user.sno + "</td>" +
												"<td>" + user.name + "</td>" +
												"<td>" + user.sc + "</td>" +
												"<td>" + user.major + "</td>" +
												"<td>" + user.clazz + "</td>" +
												"<td><a href='#'>查看详情</a></td>" +
											 "</tr>";	
						} else {
							var trTagTbody = "<tr id='" + i + "'>" +
												"<td>" + user.sno + "</td>" +
												"<td>" + user.name + "</td>" +
												"<td>" + user.sc + "</td>" +
												"<td>" + user.major + "</td>" +
												"<td>" + user.clazz + "</td>" +
												"<td><a href='#'>查看详情</a></td>" +
											 "</tr>";	
						}
						queryResultTableTbody.append(trTagTbody);
						var id = '#' + i;
						$(id).data('user', user);
					}
				}
				
				var isUsersLengthMoreThanRecordNumOfPerPage = false;
				if(users.length <= recordNumOfPerPage) {
					appendUsersToTbody(users);
				} else {
					isUsersLengthMoreThanRecordNumOfPerPage = true;
					appendUsersToTbody(users.slice(0, recordNumOfPerPage));
				}
				
				/**
				 * Append Pages To TFooter
				 * 
				 * Params: 
				 *   appendedPages: visible page number - 1
				 *   current: index of appendedPages array
				 */
				function appendPagesToTfoot(appendedPages, current) {
					var trTagTfoot = '<tr><td colspan="6"><div class="pagination"><a name="first">&laquo; 第一页</a><a id="previous" name="previous">&laquo; 上一页</a>';
					var trTagTfootEnd = '<a id="next" name="next">下一页 &raquo;</a><a name="last">最后一页 &raquo;</a><span>总记录数：' + users.length + ' 条</span></div></td></tr>';
					
					for(var i=0; i < appendedPages.length; i++) {
						if(appendedPages[i] == '...') {
							trTagTfoot += '<span>...</span>';
						} else {
							if(i == current) {
								trTagTfoot += '<a href="' + appendedPages[i] + '" class="number current">' + (appendedPages[i] + 1) + '</a>';
							} else {
								trTagTfoot += '<a href="' + appendedPages[i] + '" class="number">' + (appendedPages[i] + 1) + '</a>';
							}
						}
					}
					trTagTfoot += trTagTfootEnd;
					queryResultTableTfoot.append(trTagTfoot);
					
					var currentPage = appendedPages[current];
					$('#previous').attr('href', currentPage - 1);
					$('#next').attr('href', currentPage + 1);
					
					if(currentPage == 0) {
						$('#previous').attr('href', 0);
					}
					if(currentPage == (totalPages - 1)) {
						$('#next').attr('href', (totalPages - 1));
					}
				}
				
				var isTotalPagesMoreThanVisiblePages = false; 
				var appendedPages = [];
				if(totalPages <= visiblePages) {
					for(var i=0; i < totalPages; i++) {
						appendedPages.push(i);	
					}
				} else {
					isTotalPagesMoreThanVisiblePages = true;
					for(var i=0; i < visiblePages; i++) {
						appendedPages.push(i);	
					}
					appendedPages.push('...');
				}
				appendPagesToTfoot(appendedPages, 0);
				
				/**
				 * Pagination
				 */
				queryResultTableTfoot.find('a').live('click', function() {
					queryResultTableTbody.empty();
					var paginationDiv = queryResultTableTfoot.find('div.pagination');
					var nameAttr = $(this).attr('name');

					if(nameAttr == 'first') {
						queryResultTableTfoot.empty();
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(0, recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
						} else {
							for(var i=0; i < visiblePages; i++) {
								appendedPages.push(i);	
							}
							appendedPages.push('...');
						}
						appendPagesToTfoot(appendedPages, 0);
					} else if(nameAttr == 'last') {
						queryResultTableTfoot.empty();
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							if(remainder == 0) {
								appendUsersToTbody(users.slice(users.length - recordNumOfPerPage, users.length));
							} else {
								appendUsersToTbody(users.slice(users.length - remainder, users.length));
							}
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, totalPages - 1);
						} else {
							appendedPages.push('...');
							for(var i=(totalPages - visiblePages); i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, visiblePages);
						}
					} else if(nameAttr == 'previous') {
						var previousPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(previousPage * recordNumOfPerPage, previousPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, previousPage);
						} else {
							var currentPage = previousPage + 1;
							var nextPage = parseInt($(this).siblings('[name="next"]').attr('href'));
							if(previousPage == 0  && nextPage == 1) {
								currentPage = 0;
							}
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							
							if(numberPages[0] == currentPage) {
								if(numberPages[0] > 1) {
									appendedPages.push('...');
								}
								if(numberPages[0] == 0){
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i]);
									}
								} else {
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i] - 1);
									}
								}
								appendedPages.push('...');
								if(numberPages[0] > 1){
									appendPagesToTfoot(appendedPages, 1);
								} else {
									appendPagesToTfoot(appendedPages, 0);
								}
							} else {
								if(numberPages[0] != 0) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									appendedPages.push(numberPages[i]);
								}
								if(numberPages[visiblePages - 1] != (totalPages - 1)) {
									appendedPages.push('...');
								}
								
								for(var i=0; i < numberPages.length; i++) {
									if(numberPages[i] == currentPage) {
										if(numberPages[0] != 0) {
											appendPagesToTfoot(appendedPages, i);
										} else {
											appendPagesToTfoot(appendedPages, i - 1);
										}
										break;
									}
								}
							}
						}
					} else if(nameAttr == 'next') {
						var nextPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(nextPage * recordNumOfPerPage, nextPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, nextPage);
						} else {
							var currentPage = nextPage - 1;
							var previousPage = parseInt($(this).siblings('[name="previous"]').attr('href'));
							if(nextPage == (totalPages - 1)  && previousPage == (totalPages - 2)) {
								currentPage = totalPages - 1;
							}
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							
							if(numberPages[visiblePages - 1] == currentPage) {
								appendedPages.push('...');
								if(numberPages[visiblePages - 1] == (totalPages - 1)){
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i]);
									}
								} else {
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i] + 1);
									}
								}
								if(numberPages[visiblePages - 1] < (totalPages - 2)) {
									appendedPages.push('...');
								}
								appendPagesToTfoot(appendedPages, visiblePages);
							} else {
								if(numberPages[0] != 0) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									appendedPages.push(numberPages[i]);
								}
								if(numberPages[visiblePages - 1] != (totalPages - 1)) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									if(numberPages[i] == currentPage) {
										if(numberPages[0] != 0) {
											appendPagesToTfoot(appendedPages, i + 2);
										} else {
											appendPagesToTfoot(appendedPages, i + 1);
										}
										break;
									}
								}
							}
						}
					} else {
						var choosedPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(choosedPage * recordNumOfPerPage, choosedPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, choosedPage);
						} else {
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							if(numberPages[0] != 0) {
								appendedPages.push('...');
							}
							for(var i=0; i < numberPages.length; i++) {
								appendedPages.push(numberPages[i]);
							}
							if(numberPages[visiblePages - 1] != (totalPages - 1)) {
								appendedPages.push('...');
							}
							
							for(var i=0; i < numberPages.length; i++) {
								if(numberPages[i] == choosedPage) {
									if(numberPages[0] != 0) {
										appendPagesToTfoot(appendedPages, i + 1);
									} else {
										appendPagesToTfoot(appendedPages, i);
									}
									break;
								}
							}
						}
					}
					return false;
				});
				
				queryResultTableTbody.find('a').click(function() {
					var id = $(this).parent().parent().attr('id');
					var user = $('#' + id).data('user');
					
					var $ts = $('#ts');
					var $tas = $('#tas');
					var $nopi = $('#nopi');
					var $pi = $('#pi');
					var $noni = $('#noni');
					var $ni = $('#ni');
					var $qth = $('#qth');
					var $qpzz = $('#qpzz');
					var $rjgxmg = $('#rjgxmg');
					var $yy = $('#yy');
					var $jl = $('#jl');
					var $dd = $('#dd');
					var $kb = $('#kb');
					var $pz = $('#pz');
					var $jsbx = $('#jsbx');
					var $qt = $('#qt');
					
					$ts.next().text(user.ts);
					$tas.next().text(user.tas);
					$nopi.next().text(user.nopi);
					
					var piS = '';
					for(var i=0; i < user.pi.length; i++) {
						piS += user.pi[i] + ',';
					}
					piS = piS.substring(0, piS.lastIndexOf(','));
					$pi.next().find('div.wrap').text(piS);
					$noni.next().text(user.noni);
					var niS = '';
					for(var i=0; i < user.ni.length; i++) {
						niS += user.ni[i] + ',';
					}
					niS = niS.substring(0, niS.lastIndexOf(','));
					$ni.next().find('div.wrap').text(niS);
					
					$qth.next().text(user.fas.qth);
					$qpzz.next().text(user.fas.qpzz);
					$rjgxmg.next().text(user.fas.rjgxmg);
					$yy.next().text(user.fas.yy);
					$jl.next().text(user.fas.jl);
					$dd.next().text(user.fas.dd);
					$kb.next().text(user.fas.kb);
					$pz.next().text(user.fas.pz);
					$jsbx.next().text(user.fas.jsbx);
					$qt.next().text(user.fas.qt);
					
					$.facebox({div: '#detail-info'});
					return false;
				});
			});
		}
	});
	
	/**
 	 * Student Info Query
 	 */
	$('#sBtnStudent').live('click', function() {
		
		var $body = $('body');
		var studentInfoQueryForm = $(this).parent().parent();
		
		var clazz = studentInfoQueryForm.find('#clazz');
		var sno = studentInfoQueryForm.find('#sno');
		var name = studentInfoQueryForm.find('#name');
		var age = studentInfoQueryForm.find('#age');
		
		if(clazz.val() != $body.data(clazz.attr('id')) && !/^[A-Za-z]\d{4}$/.test(clazz.val())) {
			alert("输入有错，请检查所输入班级...");
			return;
		}
		if(sno.val() != $body.data(sno.attr('id')) && !/^\d{11,13}$/.test(sno.val())) {
			alert("输入有错，请检查所输入学号...");
			return;
		}
		if(age.val() != $body.data(age.attr('id')) && !/^\d{2,3}$/.test(age.val())) {
			alert("输入有错，请检查所输入年龄...");
			return;
		}
		
		$(document).trigger('close.facebox');
		setTimeout(queryUsers,250);
		
		function queryUsers() {
			if(clazz.val() == $body.data(clazz.attr('id'))) {
				clazz.val('-1');
			}
			if(sno.val() == $body.data(sno.attr('id'))) {
				sno.val('-1');
			}
			if(name.val() == $body.data(name.attr('id'))) {
				name.val('-1');
			}
			if(age.val() == $body.data(age.attr('id'))) {
				age.val('-1');
			}
			
			$.post(studentInfoQueryForm.attr('action'), studentInfoQueryForm.serialize(), function(resp) {
				var users = $.parseJSON(resp);
				
				var queryResultTable = $('#query-result-table');
				var queryResultTableTbody = queryResultTable.find('tbody');
				var queryResultTableTfoot = queryResultTable.find('tfoot');
				queryResultTableTbody.empty();
				queryResultTableTfoot.empty();
			
				var recordNumOfPerPage = 10;
				var visiblePages = 5;
				var totalPages = Math.ceil(users.length / recordNumOfPerPage);
				var remainder = users.length % recordNumOfPerPage;

				if(users.length == 0) {
					queryResultTableTbody.append("<tr><td colspan='6' style='padding:50px 0 50px 0;'>您所查询的数据不存在。</td></tr>");
					return;
				}
				
				/**
				 * Append Users To TBody
				 */
				function appendUsersToTbody(appendedUsers) {
					for(var i=0; i < appendedUsers.length; i++) {
						var user = appendedUsers[i];
						if(i % 2 == 0) {
							var trTagTbody = "<tr id='" + i + "' class='alt-row'>" +
												"<td>" + user.sno + "</td>" +
												"<td>" + user.name + "</td>" +
												"<td>" + user.sc + "</td>" +
												"<td>" + user.major + "</td>" +
												"<td>" + user.clazz + "</td>" +
												"<td><a href='#'>个人详情</a></td>" +
											 "</tr>";	
						} else {
							var trTagTbody = "<tr id='" + i + "'>" +
												"<td>" + user.sno + "</td>" +
												"<td>" + user.name + "</td>" +
												"<td>" + user.sc + "</td>" +
												"<td>" + user.major + "</td>" +
												"<td>" + user.clazz + "</td>" +
												"<td><a href='#'>个人详情</a></td>" +
											 "</tr>";	
						}
						queryResultTableTbody.append(trTagTbody);
						var id = '#' + i;
						$(id).data('user', user);
					}
				}
				
				var isUsersLengthMoreThanRecordNumOfPerPage = false;
				if(users.length <= recordNumOfPerPage) {
					appendUsersToTbody(users);
				} else {
					isUsersLengthMoreThanRecordNumOfPerPage = true;
					appendUsersToTbody(users.slice(0, recordNumOfPerPage));
				}
				
				/**
				 * Append Pages To TFooter
				 * 
				 * Params: 
				 *   appendedPages: visible page number - 1
				 *   current: index of appendedPages array
				 */
				function appendPagesToTfoot(appendedPages, current) {
					var trTagTfoot = '<tr><td colspan="6"><div class="pagination"><a name="first">&laquo; 第一页</a><a id="previous" name="previous">&laquo; 上一页</a>';
					var trTagTfootEnd = '<a id="next" name="next">下一页 &raquo;</a><a name="last">最后一页 &raquo;</a><span>总记录数：' + users.length + ' 条</span></div></td></tr>';
					
					for(var i=0; i < appendedPages.length; i++) {
						if(appendedPages[i] == '...') {
							trTagTfoot += '<span>...</span>';
						} else {
							if(i == current) {
								trTagTfoot += '<a href="' + appendedPages[i] + '" class="number current">' + (appendedPages[i] + 1) + '</a>';
							} else {
								trTagTfoot += '<a href="' + appendedPages[i] + '" class="number">' + (appendedPages[i] + 1) + '</a>';
							}
						}
					}
					trTagTfoot += trTagTfootEnd;
					queryResultTableTfoot.append(trTagTfoot);
					
					var currentPage = appendedPages[current];
					$('#previous').attr('href', currentPage - 1);
					$('#next').attr('href', currentPage + 1);
					
					if(currentPage == 0) {
						$('#previous').attr('href', 0);
					}
					if(currentPage == (totalPages - 1)) {
						$('#next').attr('href', (totalPages - 1));
					}
				}
				
				var isTotalPagesMoreThanVisiblePages = false; 
				var appendedPages = [];
				if(totalPages <= visiblePages) {
					for(var i=0; i < totalPages; i++) {
						appendedPages.push(i);	
					}
				} else {
					isTotalPagesMoreThanVisiblePages = true;
					for(var i=0; i < visiblePages; i++) {
						appendedPages.push(i);	
					}
					appendedPages.push('...');
				}
				appendPagesToTfoot(appendedPages, 0);
				
				/**
				 * Pagination
				 */
				queryResultTableTfoot.find('a').live('click', function() {
					queryResultTableTbody.empty();
					var paginationDiv = queryResultTableTfoot.find('div.pagination');
					var nameAttr = $(this).attr('name');

					if(nameAttr == 'first') {
						queryResultTableTfoot.empty();
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(0, recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
						} else {
							for(var i=0; i < visiblePages; i++) {
								appendedPages.push(i);	
							}
							appendedPages.push('...');
						}
						appendPagesToTfoot(appendedPages, 0);
					} else if(nameAttr == 'last') {
						queryResultTableTfoot.empty();
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							if(remainder == 0) {
								appendUsersToTbody(users.slice(users.length - recordNumOfPerPage, users.length));
							} else {
								appendUsersToTbody(users.slice(users.length - remainder, users.length));
							}
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, totalPages - 1);
						} else {
							appendedPages.push('...');
							for(var i=(totalPages - visiblePages); i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, visiblePages);
						}
					} else if(nameAttr == 'previous') {
						var previousPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(previousPage * recordNumOfPerPage, previousPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, previousPage);
						} else {
							var currentPage = previousPage + 1;
							var nextPage = parseInt($(this).siblings('[name="next"]').attr('href'));
							if(previousPage == 0  && nextPage == 1) {
								currentPage = 0;
							}
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							
							if(numberPages[0] == currentPage) {
								if(numberPages[0] > 1) {
									appendedPages.push('...');
								}
								if(numberPages[0] == 0){
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i]);
									}
								} else {
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i] - 1);
									}
								}
								appendedPages.push('...');
								if(numberPages[0] > 1){
									appendPagesToTfoot(appendedPages, 1);
								} else {
									appendPagesToTfoot(appendedPages, 0);
								}
							} else {
								if(numberPages[0] != 0) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									appendedPages.push(numberPages[i]);
								}
								if(numberPages[visiblePages - 1] != (totalPages - 1)) {
									appendedPages.push('...');
								}
								
								for(var i=0; i < numberPages.length; i++) {
									if(numberPages[i] == currentPage) {
										if(numberPages[0] != 0) {
											appendPagesToTfoot(appendedPages, i);
										} else {
											appendPagesToTfoot(appendedPages, i - 1);
										}
										break;
									}
								}
							}
						}
					} else if(nameAttr == 'next') {
						var nextPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(nextPage * recordNumOfPerPage, nextPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, nextPage);
						} else {
							var currentPage = nextPage - 1;
							var previousPage = parseInt($(this).siblings('[name="previous"]').attr('href'));
							if(nextPage == (totalPages - 1)  && previousPage == (totalPages - 2)) {
								currentPage = totalPages - 1;
							}
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							
							if(numberPages[visiblePages - 1] == currentPage) {
								appendedPages.push('...');
								if(numberPages[visiblePages - 1] == (totalPages - 1)){
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i]);
									}
								} else {
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i] + 1);
									}
								}
								if(numberPages[visiblePages - 1] < (totalPages - 2)) {
									appendedPages.push('...');
								}
								appendPagesToTfoot(appendedPages, visiblePages);
							} else {
								if(numberPages[0] != 0) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									appendedPages.push(numberPages[i]);
								}
								if(numberPages[visiblePages - 1] != (totalPages - 1)) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									if(numberPages[i] == currentPage) {
										if(numberPages[0] != 0) {
											appendPagesToTfoot(appendedPages, i + 2);
										} else {
											appendPagesToTfoot(appendedPages, i + 1);
										}
										break;
									}
								}
							}
						}
					} else {
						var choosedPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(choosedPage * recordNumOfPerPage, choosedPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, choosedPage);
						} else {
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							if(numberPages[0] != 0) {
								appendedPages.push('...');
							}
							for(var i=0; i < numberPages.length; i++) {
								appendedPages.push(numberPages[i]);
							}
							if(numberPages[visiblePages - 1] != (totalPages - 1)) {
								appendedPages.push('...');
							}
							
							for(var i=0; i < numberPages.length; i++) {
								if(numberPages[i] == choosedPage) {
									if(numberPages[0] != 0) {
										appendPagesToTfoot(appendedPages, i + 1);
									} else {
										appendPagesToTfoot(appendedPages, i);
									}
									break;
								}
							}
						}
					}
					return false;
				});
				
				queryResultTableTbody.find('a').click(function() {
					var id = $(this).parent().parent().attr('id');
					var user = $('#' + id).data('user');
					
					var $bornPlace = $('#bornPlace');
					var $healthStatus = $('#healthStatus');
					var $raiseMethod = $('#raiseMethod');
					var $relativesHealth = $('#relativesHealth');
					var $willConsult = $('#willConsult');
					var $havePessiThoughts = $('#havePessiThoughts');
					
					$bornPlace.next().text(user.bornPlace);
					$healthStatus.next().text(user.healthStatus);
					$raiseMethod.next().text(user.raiseMethod);
					$relativesHealth.next().text(user.relativesHealth);
					$willConsult.next().text(user.willConsult);
					$havePessiThoughts.next().text(user.havePessiThoughts);
					
					$.facebox({div: '#detail-info'});
					return false;
				});
			});
		}
	});
	
	/**
 	 * Teacher Info Query
 	 */
	$('#sBtnTeacher').live('click', function() {
		
		var $body = $('body');
		var teacherInfoQueryForm = $(this).parent().parent();
		var tid = teacherInfoQueryForm.find('#tid');
		
		if(tid.val() != $body.data(tid.attr('id')) && !/^\d+$/.test(tid.val())) {
			alert("输入有错，请检查所输入教师号...");
			return;
		}
		
		$(document).trigger('close.facebox');
		setTimeout(queryUsers,250);
		
		function queryUsers() {
			if(tid.val() == $body.data(tid.attr('id'))) {
				tid.val('-1');
			}
			
			$.post(teacherInfoQueryForm.attr('action'), teacherInfoQueryForm.serialize(), function(resp) {
				var users = $.parseJSON(resp);
				
				var queryResultTable = $('#query-result-table');
				var queryResultTableTbody = queryResultTable.find('tbody');
				var queryResultTableTfoot = queryResultTable.find('tfoot');
				queryResultTableTbody.empty();
				queryResultTableTfoot.empty();
			
				var recordNumOfPerPage = 10;
				var visiblePages = 5;
				var totalPages = Math.ceil(users.length / recordNumOfPerPage);
				var remainder = users.length % recordNumOfPerPage;

				if(users.length == 0) {
					queryResultTableTbody.append("<tr><td colspan='6' style='padding:50px 0 50px 0;'>您所查询的数据不存在。</td></tr>");
					return;
				}
				
				/**
				 * Append Users To TBody
				 */
				function appendUsersToTbody(appendedUsers) {
					for(var i=0; i < appendedUsers.length; i++) {
						var user = appendedUsers[i];
						if(i % 2 == 0) {
							var trTagTbody = "<tr id='" + i + "' class='alt-row'>" +
												"<td>" + user.teacherId + "</td>" +
												"<td>" + user.password + "</td>" +
												"<td>" + user.privilege + "</td>" +
												"<td><a href='/psytest-webapp/user/" + user.teacherId + "/delete'>删除</a></td>" +
											 "</tr>";	
						} else {
							var trTagTbody = "<tr id='" + i + "'>" +
												"<td>" + user.teacherId + "</td>" +
												"<td>" + user.password + "</td>" +
												"<td>" + user.privilege + "</td>" +
												"<td><a href='/psytest-webapp/user/" + user.teacherId + "/delete'>删除</a></td>" +
											 "</tr>";	
						}
						queryResultTableTbody.append(trTagTbody);
						var id = '#' + i;
						$(id).data('user', user);
					}
				}
				
				var isUsersLengthMoreThanRecordNumOfPerPage = false;
				if(users.length <= recordNumOfPerPage) {
					appendUsersToTbody(users);
				} else {
					isUsersLengthMoreThanRecordNumOfPerPage = true;
					appendUsersToTbody(users.slice(0, recordNumOfPerPage));
				}
				
				/**
				 * Append Pages To TFooter
				 * 
				 * Params: 
				 *   appendedPages: visible page number - 1
				 *   current: index of appendedPages array
				 */
				function appendPagesToTfoot(appendedPages, current) {
					var trTagTfoot = '<tr><td colspan="6"><div class="pagination"><a name="first">&laquo; 第一页</a><a id="previous" name="previous">&laquo; 上一页</a>';
					var trTagTfootEnd = '<a id="next" name="next">下一页 &raquo;</a><a name="last">最后一页 &raquo;</a><span>总记录数：' + users.length + ' 条</span></div></td></tr>';
					
					for(var i=0; i < appendedPages.length; i++) {
						if(appendedPages[i] == '...') {
							trTagTfoot += '<span>...</span>';
						} else {
							if(i == current) {
								trTagTfoot += '<a href="' + appendedPages[i] + '" class="number current">' + (appendedPages[i] + 1) + '</a>';
							} else {
								trTagTfoot += '<a href="' + appendedPages[i] + '" class="number">' + (appendedPages[i] + 1) + '</a>';
							}
						}
					}
					trTagTfoot += trTagTfootEnd;
					queryResultTableTfoot.append(trTagTfoot);
					
					var currentPage = appendedPages[current];
					$('#previous').attr('href', currentPage - 1);
					$('#next').attr('href', currentPage + 1);
					
					if(currentPage == 0) {
						$('#previous').attr('href', 0);
					}
					if(currentPage == (totalPages - 1)) {
						$('#next').attr('href', (totalPages - 1));
					}
				}
				
				var isTotalPagesMoreThanVisiblePages = false; 
				var appendedPages = [];
				if(totalPages <= visiblePages) {
					for(var i=0; i < totalPages; i++) {
						appendedPages.push(i);	
					}
				} else {
					isTotalPagesMoreThanVisiblePages = true;
					for(var i=0; i < visiblePages; i++) {
						appendedPages.push(i);	
					}
					appendedPages.push('...');
				}
				appendPagesToTfoot(appendedPages, 0);
				
				/**
				 * Pagination
				 */
				queryResultTableTfoot.find('a').live('click', function() {
					queryResultTableTbody.empty();
					var paginationDiv = queryResultTableTfoot.find('div.pagination');
					var nameAttr = $(this).attr('name');

					if(nameAttr == 'first') {
						queryResultTableTfoot.empty();
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(0, recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
						} else {
							for(var i=0; i < visiblePages; i++) {
								appendedPages.push(i);	
							}
							appendedPages.push('...');
						}
						appendPagesToTfoot(appendedPages, 0);
					} else if(nameAttr == 'last') {
						queryResultTableTfoot.empty();
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							if(remainder == 0) {
								appendUsersToTbody(users.slice(users.length - recordNumOfPerPage, users.length));
							} else {
								appendUsersToTbody(users.slice(users.length - remainder, users.length));
							}
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, totalPages - 1);
						} else {
							appendedPages.push('...');
							for(var i=(totalPages - visiblePages); i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, visiblePages);
						}
					} else if(nameAttr == 'previous') {
						var previousPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(previousPage * recordNumOfPerPage, previousPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, previousPage);
						} else {
							var currentPage = previousPage + 1;
							var nextPage = parseInt($(this).siblings('[name="next"]').attr('href'));
							if(previousPage == 0  && nextPage == 1) {
								currentPage = 0;
							}
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							
							if(numberPages[0] == currentPage) {
								if(numberPages[0] > 1) {
									appendedPages.push('...');
								}
								if(numberPages[0] == 0){
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i]);
									}
								} else {
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i] - 1);
									}
								}
								appendedPages.push('...');
								if(numberPages[0] > 1){
									appendPagesToTfoot(appendedPages, 1);
								} else {
									appendPagesToTfoot(appendedPages, 0);
								}
							} else {
								if(numberPages[0] != 0) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									appendedPages.push(numberPages[i]);
								}
								if(numberPages[visiblePages - 1] != (totalPages - 1)) {
									appendedPages.push('...');
								}
								
								for(var i=0; i < numberPages.length; i++) {
									if(numberPages[i] == currentPage) {
										if(numberPages[0] != 0) {
											appendPagesToTfoot(appendedPages, i);
										} else {
											appendPagesToTfoot(appendedPages, i - 1);
										}
										break;
									}
								}
							}
						}
					} else if(nameAttr == 'next') {
						var nextPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(nextPage * recordNumOfPerPage, nextPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, nextPage);
						} else {
							var currentPage = nextPage - 1;
							var previousPage = parseInt($(this).siblings('[name="previous"]').attr('href'));
							if(nextPage == (totalPages - 1)  && previousPage == (totalPages - 2)) {
								currentPage = totalPages - 1;
							}
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							
							if(numberPages[visiblePages - 1] == currentPage) {
								appendedPages.push('...');
								if(numberPages[visiblePages - 1] == (totalPages - 1)){
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i]);
									}
								} else {
									for(var i=0; i < numberPages.length; i++) {
										appendedPages.push(numberPages[i] + 1);
									}
								}
								if(numberPages[visiblePages - 1] < (totalPages - 2)) {
									appendedPages.push('...');
								}
								appendPagesToTfoot(appendedPages, visiblePages);
							} else {
								if(numberPages[0] != 0) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									appendedPages.push(numberPages[i]);
								}
								if(numberPages[visiblePages - 1] != (totalPages - 1)) {
									appendedPages.push('...');
								}
								for(var i=0; i < numberPages.length; i++) {
									if(numberPages[i] == currentPage) {
										if(numberPages[0] != 0) {
											appendPagesToTfoot(appendedPages, i + 2);
										} else {
											appendPagesToTfoot(appendedPages, i + 1);
										}
										break;
									}
								}
							}
						}
					} else {
						var choosedPage = parseInt($(this).attr('href'));
						if(!isUsersLengthMoreThanRecordNumOfPerPage) {
							appendUsersToTbody(users);
						} else {
							appendUsersToTbody(users.slice(choosedPage * recordNumOfPerPage, choosedPage * recordNumOfPerPage + recordNumOfPerPage));
						}
						
						appendedPages = [];
						if(!isTotalPagesMoreThanVisiblePages) {
							queryResultTableTfoot.empty();
							for(var i=0; i < totalPages; i++) {
								appendedPages.push(i);	
							}
							appendPagesToTfoot(appendedPages, choosedPage);
						} else {
							var numberPages = []; 
							paginationDiv.find('a.number').each(function() {
								numberPages.push(parseInt($(this).attr('href')));
							});
							queryResultTableTfoot.empty();
							if(numberPages[0] != 0) {
								appendedPages.push('...');
							}
							for(var i=0; i < numberPages.length; i++) {
								appendedPages.push(numberPages[i]);
							}
							if(numberPages[visiblePages - 1] != (totalPages - 1)) {
								appendedPages.push('...');
							}
							
							for(var i=0; i < numberPages.length; i++) {
								if(numberPages[i] == choosedPage) {
									if(numberPages[0] != 0) {
										appendPagesToTfoot(appendedPages, i + 1);
									} else {
										appendPagesToTfoot(appendedPages, i);
									}
									break;
								}
							}
						}
					}
					return false;
				});
				
				queryResultTableTbody.find('a').click(function() {
					if(!confirm("确认删除该用户?")) {
						return false;
					}
					$.ajax({
						url: $(this).attr('href'),
						cache: false,
						success: function(msg) {
							queryUsers();
							alert(msg);
						}
					});
					return false;
				});
			});
		}
	});
	
	/**
 	 * Add Teacher
 	 */
	$('#sBtnTeacherReg').live('click', function() {
		
		var $body = $('body');
		var teacherRegisterForm = $(this).parent().parent();
		var teacherId = teacherRegisterForm.find('#teacherId');
		var password = teacherRegisterForm.find('#password');
		var privilegeReg = teacherRegisterForm.find('#privilegeReg');
		
		if(!/^\d+$/.test(teacherId.val())) {
			alert("输入有错，请检查所输入教师号...");
			return;
		}
		if(password.val() == $body.data(password.attr('id'))) {
			alert("输入有错，请检查所输入密码...");
			return
		}
		if(privilegeReg.val() == '-1') {
			alert("输入有错，请检查所选学院...");
			return
		}
		
		$(document).trigger('close.facebox');
		setTimeout(postData,250);
		
		function postData() {
			$.post(teacherRegisterForm.attr('action'), teacherRegisterForm.serialize(), function(msg) {
				alert(msg);
			});
		}
	});
});